import axios from '../api'
import { categoryData } from '~/logic'

export function batch(ids: any[]) {
  return new Promise((resolve) => {
    // 去重相同的id
    ids = [...new Set(ids)]
    const cacheData: any = {}
    for (let i = 0; i < ids.length; i++) {
      const id = ids[i]
      if (Object.keys(categoryData).includes(id)) {
        cacheData[id] = categoryData[id]
        // 从ids中移除
        ids.splice(i, 1)
      }
    }
    if (ids.length > 0) {
      axios.post('/Category/batch', {
        ids: ids.join(','),
      }).then((res) => {
        for (const resKey in res.data.data)
          categoryData[resKey] = res.data.data[resKey]
        // 将cacheData数据注入res.data.data
        res.data.data = Object.assign(cacheData, res.data.data)
        resolve(res)
      }).catch((reject) => {
        resolve({ data: { data: cacheData } })
      })
    }
    else {
      resolve({ data: { data: cacheData } })
    }
  })
}
